package com.orangelife.mobile.individual.activity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.curry.android.http.HttpUtil;
import com.curry.android.util.DialogHelper;
import com.curry.android.util.SystemInfoUtil;
import com.curry.orangelife.mobile.R;
import com.markupartist.android.widget.PullToRefreshListView;
import com.markupartist.android.widget.PullToRefreshListView.IXListViewListener;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.common.biz.JSONRequest;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.individual.adapter.BalanceDetailAdapter;
import com.orangelife.mobile.util.JsonReponseHandler;
import com.ta.utdid2.android.utils.SystemUtils;

/**
 * 收支明细
 *
 * @author Administrator
 */
public class BalanceDetailActivity extends OrangeLifeBaseActivity {
    /**
     * 一页中数据的条数，初始设置为7条
     */
    private int pageSize = Constant.PAGE_SIZE_DEFAULLT;
    /**
     * 初始页，初始化为第一页
     */
    private int pageNo = Constant.PAGE_NO_DEFAULT;
    private int flags = 1;
    private TextView tvTitle;
    private LinearLayout llRight;
    private RelativeLayout rl_title;
    private PullToRefreshListView lvBalanceDetail;
    private BalanceDetailAdapter<Map<String, Object>> balanceAdapter;
    private List<Map<String, Object>> mapList;
    private List<Map<String, Object>> newList;
    private Handler mHandler;
    private String walletID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_balance_detail);
        walletID = getIntent().getExtras().getString("walletID");
        initView();
        setAdapter();
        pullListView();
        getListFromServer(pageSize, pageNo);
    }

    private void pullListView() {
        showDialog(this);
        lvBalanceDetail.setXListViewListener(new IXListViewListener() {
            @Override
            public void onRefresh() {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        flags = 1;
                        pageNo = 1;
                        updateListViewData();
                    }
                }, 2000);
            }

            @Override
            public void onLoadMore() {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        flags = 0;
                        pageNo += 1;
                        updateListViewData();
                    }
                }, 2000);

            }
        });
    }

    private void updateListViewData() {
        getListFromServer(pageSize, pageNo);
        onLoad();
        if (mapList != null) {
            balanceAdapter.setList(mapList);
            balanceAdapter.notifyDataSetChanged();
        }
    }

    private void onLoad() {
        lvBalanceDetail.stopRefresh();
        lvBalanceDetail.stopLoadMore();
        lvBalanceDetail.setRefreshTime(new Date().toLocaleString());
    }

    private void getListFromServer(int pageSize, int pageNo) {
        String url = Constant.URL_BALANCE_DETAIL;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("type", select);
        map.put("walletID", walletID);
        map.put("pageIndex", pageNo);
        map.put("pageSize", pageSize);
        JSONRequest.getInstance().sendRequest(JSONRequest.GET, url, map, handler, 0, HttpUtil.ACTION_URI);
    }

    private void setAdapter() {
        balanceAdapter = new BalanceDetailAdapter<Map<String, Object>>(this, R.layout.item_lv_balance_detail, mapList);
        balanceAdapter.addField("remark", R.id.tvBalanceTitle);
        balanceAdapter.addField("money", R.id.tvBalancePrice);
        balanceAdapter.addField("tscreate", R.id.tvBalanceTime);
        lvBalanceDetail.setAdapter(balanceAdapter);
        balanceAdapter.notifyDataSetChanged();
    }

    private void initView() {
        mHandler = new Handler();
        mapList = new ArrayList<Map<String, Object>>();
        tvTitle = (TextView) findViewById(R.id.tv_title);
        llRight = (LinearLayout) findViewById(R.id.ll_right);
        rl_title = (RelativeLayout) findViewById(R.id.rl_title);
        lvBalanceDetail = (PullToRefreshListView) findViewById(R.id.lvBalanceDetail);
        tvTitle.setText(getResources().getString(R.string.balance_detail));
        llRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupWindow();
            }
        });
    }

    private String[] screen;
    private int[] myDrawable = {R.drawable.ic_balance_1,
            R.drawable.ic_balance_2,
            R.drawable.ic_balance_3,
            R.drawable.ic_balance_4,
            R.drawable.ic_balance_5};
    private int select = 0;
    private PopupWindow popupWindow;
    private View view;
    private ListView lv_group;

    private void showPopupWindow() {
        if (popupWindow == null) {
            LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = layoutInflater.inflate(R.layout.popwin_screen, null);
            lv_group = (ListView) view.findViewById(R.id.lvGroup);
            screen = this.getResources().getStringArray(R.array.screen_list);
            GroupAdapter groupAdapter = new GroupAdapter();
			lv_group.setAdapter(groupAdapter);
            popupWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT);
        }
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
        popupWindow.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.popwin_bg));
        popupWindow.setAnimationStyle(R.style.popwin_anim_style);
//        popupWindow.showAsDropDown(rl_title);
        popupWindow.showAsDropDown(rl_title,0,0);
        lv_group.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view,
                                    int position, long id) {
                select = position;
                if (popupWindow != null) {
                    popupWindow.dismiss();
                }
                // 刷新列表
                mapList.clear();
                tvTitle.setText(screen[position]);
                flags = 1;
                pageNo = 1;
                updateListViewData();
            }
        });
    }

    private class GroupAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return screen.length;
        }

        @Override
        public Object getItem(int position) {
            return screen[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(BalanceDetailActivity.this).inflate(R.layout.item_balance_screen, null);
                holder = new ViewHolder();
                holder.ivSelected = (ImageView) convertView.findViewById(R.id.ivSelected);
                holder.ivScreen = (ImageView) convertView.findViewById(R.id.ivScreen);
                holder.tvScreen = (TextView) convertView.findViewById(R.id.tvScreen);
                holder.line = convertView.findViewById(R.id.line);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.ivScreen.setImageResource(myDrawable[position]);
            holder.tvScreen.setText(screen[position]);
            if (position == select) {
                holder.ivSelected.setVisibility(View.VISIBLE);
            } else {
                holder.ivSelected.setVisibility(View.INVISIBLE);
            }
            if (position == screen.length - 1) {
                holder.line.setVisibility(View.INVISIBLE);
            }else{
                holder.line.setVisibility(View.VISIBLE);
            }
            return convertView;
        }

        class ViewHolder {
            TextView tvScreen;
            ImageView ivScreen;
            ImageView ivSelected;
            View line;
        }
    }

    Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            closeDialog();
            switch (msg.what) {
                case 0:
                    /** 列表查询 */

                    newList = JsonReponseHandler.getListFromJson(
                            String.valueOf(msg.obj), balanceAdapter, null);
                    updateListView(newList);
                    break;

                default:
                    break;
            }
        }

        ;
    };

    private void updateListView(List<Map<String, Object>> newList) {
        if (newList == null) {
            lvBalanceDetail.setPullLoadEnable(false);
            if (flags == 1) {
                mapList.clear();
                balanceAdapter.setList(mapList);
                balanceAdapter.notifyDataSetChanged();
            }
        }
        if (mapList != null && newList != null) {
            if (newList.size() == 0) {
                balanceAdapter.setList(mapList);
                balanceAdapter.notifyDataSetChanged();
                lvBalanceDetail.setPullLoadEnable(false);
            } else {
                if (flags == 1) {
                    mapList.clear();
                }
                lvBalanceDetail.setPullLoadEnable(true);
                mapList.addAll(newList);
                balanceAdapter.setList(mapList);
                balanceAdapter.notifyDataSetChanged();
            }
        }
    }

}
